<template>
  <div class="employee-container">
    <FeatureHeader img="https://cdn-icons-png.flaticon.com/512/219/219983.png" title="人员管理" />
    <el-skeleton :loading="loading" animated>
      <template #template>
        <el-skeleton-item variant="text" style="width: 60%" />
        <el-skeleton-item variant="rect" style="height: 200px" />
      </template>
      <template #default>
        <div class="toolbar">
          <el-button type="primary" @click="handleAdd">新增员工</el-button>
          <el-input
            v-model="searchQuery"
            placeholder="搜索员工"
            style="width: 200px; margin-left: 10px"
            @input="handleSearch"
          >
            <el-button slot="append" icon="el-icon-search"></el-button>
          </el-input>
        </div>
        <BaseTable :data="filteredEmployeeList" border style="width: 100%" v-loading="loading">
          <el-table-column prop="id" label="ID" width="80"></el-table-column>
          <el-table-column prop="name" label="姓名" width="120"></el-table-column>
          <el-table-column prop="department" label="部门"></el-table-column>
          <el-table-column prop="position" label="职位"></el-table-column>
          <el-table-column prop="phone" label="电话"></el-table-column>
          <el-table-column prop="email" label="邮箱"></el-table-column>
          <el-table-column prop="status" label="状态" width="100">
            <template slot-scope="scope">
              <el-tag :type="scope.row.status === '在职' ? 'success' : 'info'">
                {{ scope.row.status }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200">
            <template slot-scope="scope">
              <el-button size="mini" @click="handleEdit(scope.row)">编辑</el-button>
              <el-button size="mini" type="danger" @click="handleDelete(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </BaseTable>
      </template>
    </el-skeleton>
    <!-- 新增/编辑对话框 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible">
      <BaseForm :model="form" :rules="rules" ref="form" label-width="80px">
        <el-form-item label="姓名" prop="name">
          <el-input v-model="form.name"></el-input>
        </el-form-item>
        <el-form-item label="部门" prop="department">
          <el-select v-model="form.department" placeholder="请选择部门">
            <el-option
              v-for="item in departments"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="职位" prop="position">
          <el-select v-model="form.position" placeholder="请选择职位">
            <el-option
              v-for="item in positions"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input v-model="form.phone"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email"></el-input>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择状态">
            <el-option label="在职" value="在职"></el-option>
            <el-option label="离职" value="离职"></el-option>
          </el-select>
        </el-form-item>
      </BaseForm>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleSubmit">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import FeatureHeader from '@/components/FeatureHeader.vue'
import BaseTable from '@/components/BaseTable.vue'
import BaseForm from '@/components/BaseForm.vue'
import { mapState, mapActions } from 'vuex'

export default {
  name: 'EmployeeList',
  components: { FeatureHeader, BaseTable, BaseForm },
  data() {
    return {
      dialogVisible: false,
      dialogTitle: '新增员工',
      form: {
        name: '',
        department: '',
        position: '',
        phone: '',
        email: '',
        status: '在职'
      },
      rules: {
        name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
        department: [{ required: true, message: '请选择部门', trigger: 'change' }],
        position: [{ required: true, message: '请选择职位', trigger: 'change' }],
        phone: [{ required: true, message: '请输入电话', trigger: 'blur' }],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
        ],
        status: [{ required: true, message: '请选择状态', trigger: 'change' }]
      },
      searchQuery: '',
      loading: true,
      editMode: false,
      departments: [
        { value: '技术部', label: '技术部' },
        { value: '人事部', label: '人事部' },
        { value: '财务部', label: '财务部' },
        { value: '市场部', label: '市场部' }
      ],
      positions: [
        { value: '经理', label: '经理' },
        { value: '主管', label: '主管' },
        { value: '员工', label: '员工' }
      ]
    }
  },
  computed: {
    ...mapState({
      employeeList: state => state.employee.list
    }),
    filteredEmployeeList() {
      if (!this.searchQuery) return this.employeeList
      const q = this.searchQuery.trim().toLowerCase()
      return this.employeeList.filter(e =>
        e.name.toLowerCase().includes(q) ||
        (e.department && e.department.toLowerCase().includes(q)) ||
        (e.position && e.position.toLowerCase().includes(q))
      )
    }
  },
  created() {
    this.fetchList()
    setTimeout(() => { this.loading = false }, 1000)
  },
  methods: {
    ...mapActions({
      fetchList: 'employee/fetchList',
      addEmployee: 'employee/addEmployee',
      editEmployee: 'employee/editEmployee',
      deleteEmployee: 'employee/deleteEmployee'
    }),
    handleAdd() {
      this.dialogTitle = '新增员工'
      this.editMode = false
      if (this.$refs.form && this.$refs.form.resetFields) {
        this.$refs.form.resetFields()
      }
      this.form = { name: '', department: '', position: '', phone: '', email: '', status: '在职' }
      this.dialogVisible = true
    },
    handleEdit(row) {
      this.dialogTitle = '编辑员工'
      this.editMode = true
      this.form = { ...row }
      this.dialogVisible = true
    },
    handleDelete(row) {
      this.$confirm('确认删除该员工?', '提示', {
        type: 'warning'
      }).then(() => {
        this.deleteEmployee(row.id)
        this.$message.success('删除成功')
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    },
    handleSubmit() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          const employeeData = { ...this.form }
          console.log('EmployeeList.vue: 表单验证成功，准备提交数据到 action:', employeeData)
          if (this.editMode) {
            this.editEmployee(employeeData)
              .then(() => {
                this.$message.success('编辑成功')
                this.dialogVisible = false
                console.log('EmployeeList.vue: editEmployee action resolved')
              })
              .catch(error => {
                console.error('EmployeeList.vue: 编辑员工失败:', error)
                this.$message.error('编辑失败')
              })
          } else {
            this.addEmployee(employeeData)
              .then(() => {
                this.$message.success('新增成功')
                this.dialogVisible = false
                console.log('EmployeeList.vue: addEmployee action resolved')
              })
              .catch(error => {
                console.error('EmployeeList.vue: 新增员工失败:', error)
                this.$message.error('新增失败')
              })
          }
        } else {
          console.log('EmployeeList.vue: 表单验证失败')
          this.$message.error('表单验证失败，请检查输入项')
          return false
        }
      })
    },
    handleSearch() {
      // 触发本地过滤即可，filteredEmployeeList会自动响应
    }
  }
}
</script>

<style scoped>
.employee-container {
  padding: 20px;
}

.toolbar {
  margin-bottom: 20px;
}
</style> 